﻿using HomagChina.Basic.CCT.Db.CCT_Db;
using HomagGroup.Base;
using HomagGroup.Base.UI;
using HomagGroup.Base.UI.Controls;
using HomagGroup.Base.UI.Themes.Resources;
using HomagGroup.Base.UI.Windows;
using HomagChina.Nesting.Views;
using PropertiesLibarary.Properties;
using Proxy;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Threading;
using static HomagChina.Nesting.ProcessResourceInternal;
using localText = PropertiesLibarary.Properties.Resources;

namespace HomagChina.Nesting
{
    public class HomeViewModel : HomagGroup.Base.UI.NotifyPropertyChangedBase
    {
        #region Command

        public RelayCommand ActionButtoClick { get; }
        public RelayCommand ClickInFeed { get; }
        public RelayCommand ClickPrinter { get; }
        public RelayCommand ClickCancelAll { get; }
        public RelayCommand ClickRunEmpty { get; }
        public RelayCommand EditCommand { get; }
        public RelayCommand DeleteCommand { get; }
        public RelayCommand OpenCommand { get; }
        public RelayCommand SearchCommand { get; }
        public RelayCommand UnLoadedCommand { get; }
        public RelayCommand LoadedCommand { get; }
        public RelayCommand RemoveMpr { get; }

        #endregion Command

        #region Conponents

        private DeviceState _InFeedState;

        public DeviceState InFeedState
        {
            get => _InFeedState;
            set { _InFeedState = value; OnPropertyChanged(); }
        }

        private DeviceState _OutFeedState;
        public string CurrentAdress { get; set; }

        public DeviceState OutFeedState
        {
            get => _OutFeedState;
            set { _OutFeedState = value; OnPropertyChanged(); }
        }

        private ObservableCollection<BatchsModel> list_BatchesModel;

        public ObservableCollection<BatchsModel> List_BatchesModel
        {
            get => list_BatchesModel;
            set { list_BatchesModel = value; OnPropertyChanged(); }
        }

        private ObservableCollection<object> removeMprList = new ObservableCollection<object>();

        public ObservableCollection<object> RemoveMprList
        {
            get => removeMprList;
            set { removeMprList = value; OnPropertyChanged(); }
        }

        private ObservableCollection<MprListModel> mprGroupBatchs = new ObservableCollection<MprListModel>();

        public ObservableCollection<MprListModel> MprGroupBatchs
        {
            get => mprGroupBatchs;
            set { mprGroupBatchs = value; OnPropertyChanged(); }
        }

        private string currentBatches;

        public string CurrentBatches
        {
            get => currentBatches;
            set { currentBatches = value; OnPropertyChanged(); }
        }

        private int? boardsAmount;

        public int? BoardsAmount
        {
            get => boardsAmount;
            set { boardsAmount = value; OnPropertyChanged(); }
        }

        private double _TotalCompletionRate;

        public double TotalCompletionRate
        {
            get => _TotalCompletionRate;
            set { _TotalCompletionRate = value; OnPropertyChanged(); }
        }

        private bool batchsSelectState = true;

        public bool BatchsSelectState
        { get => batchsSelectState; set { batchsSelectState = value; OnPropertyChanged(); } }

        private bool mprSelectedState = true;

        public bool MprSelectedState
        { get => mprSelectedState; set { mprSelectedState = value; OnPropertyChanged(); } }

        private BatchsModel currentBatchesModel;

        public BatchsModel CurrentBatchesModel
        {
            get => currentBatchesModel;
            set
            {
                currentBatchesModel = value;
                if (value != null) HandleChangeCurrentBatches();
                OnPropertyChanged();
            }
        }

        private System.Windows.Media.Brush _TableBack;

        public System.Windows.Media.Brush TableBack
        {
            get => _TableBack;
            set { _TableBack = value; OnPropertyChanged(); }
        }

        public DropDownList dropDownList { get; set; }

        #region ToggleSwitch

        private bool _InFeedCheck;

        public bool InFeedCheck
        {
            get => _InFeedCheck;
            set { _InFeedCheck = value; OnPropertyChanged(); }
        }

        private bool _InFeedEnable = true;

        public bool InFeedEnable
        {
            get => _InFeedEnable;
            set { _InFeedEnable = value; OnPropertyChanged(); }
        }

        private bool _PrinterCheck;

        public bool PrinterCheck
        {
            get => _PrinterCheck;
            set { _PrinterCheck = value; OnPropertyChanged(); }
        }

        private bool _PrinterEnable = true;

        public bool PrinterEnable
        {
            get => _PrinterEnable;
            set { _PrinterEnable = value; OnPropertyChanged(); }
        }

        #endregion ToggleSwitch

        private bool _RunEmptyCheck;

        public bool RunEmptyCheck
        {
            get => _RunEmptyCheck;
            set { _RunEmptyCheck = value; OnPropertyChanged(); }
        }

        public string RemberBatchId { get; set; } = "";

        /// <summary>
        /// Dropdown list
        /// </summary>
        public object SelectedValue;

        #region 属性

        private Canvas _warehouse;

        public Canvas Warehouse
        {
            get => _warehouse;
            set { _warehouse = value; OnPropertyChanged(); }
        }

        public Dictionary<string, StorageDataModel> StorageDataModels = new Dictionary<string, StorageDataModel>();

        #endregion 属性

        #endregion Conponents

        #region Handle

        private CommonHandle Handle_Common;
        private InsertInfoHandle Handle_Insert;
        private SearchInfoHandle Handle_Search;
        private DeleteInfoHandle Handle_Delete;
        private RunEmptyHandle Handle_RunEmpty;

        #endregion Handle

        private DispatcherTimer UpdateSessionTimer;
        public PrintHistoryDialogViewModel printHistoryDialogViewModel;
        public PartDetailsDialogViewModel partDetailsDialogViewModel;

        public HomeViewModel()
        {
            ClickInFeed = new RelayCommand(ClickInFeedCommand);
            ActionButtoClick = new RelayCommand(ActionButtoClickCommand);
            ClickPrinter = new RelayCommand(ClickPrinterCommand);
            ClickCancelAll = new RelayCommand(ClickCancelAllCommand);
            ClickRunEmpty = new RelayCommand(ClickRunEmptyCommand);
            LoadedCommand = new RelayCommand(ViewloadedCommand);
            UnLoadedCommand = new RelayCommand(ViewUnloadedCommand);

            Handle_Common = new CommonHandle();
            Handle_Insert = new InsertInfoHandle();
            Handle_Search = new SearchInfoHandle();
            Handle_Delete = new DeleteInfoHandle();
            Handle_RunEmpty = new RunEmptyHandle();
            UIAdjustments.CurrentThreadLanguageManager.CultureChanged += HandleReset;
            LoadDropDownList();
            UpdateSessionTimer = new DispatcherTimer
            {
                Interval = TimeSpan.FromMilliseconds(3000)
            };
            Refresh();
        }

        public event EventHandler RequestScrollPositionSave;

        public event EventHandler RequestScrollPositionRestore;

        private void ViewloadedCommand()
        {
            List_BatchesModel = Handle_Search.GetBatchsList();
            CurrentBatchesModel = List_BatchesModel.FirstOrDefault(s => s.BatchId == RemberBatchId) as BatchsModel;
            if (CurrentBatchesModel == null && list_BatchesModel.Count() > 0) CurrentBatchesModel = list_BatchesModel[0];
            if (MprGroupBatchs != null && MprGroupBatchs.Count > 0)
            {
                MprGroupBatchs = Handle_Search.GetBorderDetailsListByBatch(MprGroupBatchs);
                TotalCompletionRate = CurrentBatchesModel == null ? 0 : Handle_Search.GetTotalCompletionRate(RemberBatchId);
            }
        }

        private void ViewUnloadedCommand()
        {
            UpdateSessionTimer.Stop();
        }

        public void Refresh()
        {
            try
            {
                UpdateSessionTimer.Tick += (sender, args) =>
                {
                    // 通知 View 保存滚动位置
                    RequestScrollPositionSave?.Invoke(this, EventArgs.Empty);
                    List_BatchesModel = Handle_Search.GetBatchsList();
                    CurrentBatchesModel = List_BatchesModel.FirstOrDefault(s => s.BatchId == RemberBatchId) as BatchsModel;
                    if (CurrentBatchesModel == null && list_BatchesModel.Count() > 0) CurrentBatchesModel = list_BatchesModel[0];
                    if (MprGroupBatchs != null && MprGroupBatchs.Count > 0)
                    {
                        MprGroupBatchs = Handle_Search.GetBorderDetailsListByBatch(MprGroupBatchs);
                        TotalCompletionRate = CurrentBatchesModel == null ? 0 : Handle_Search.GetTotalCompletionRate(RemberBatchId);
                    }
                    // 通知 View 恢复滚动位置
                    RequestScrollPositionRestore?.Invoke(this, EventArgs.Empty);
                    //完成当前批次 恢复按钮状态
                    if (TotalCompletionRate == 100)
                    {
                        TableBack = null;
                        Dictionary<string, RouterItemDataModel> RouterDictionary = (Dictionary<string, RouterItemDataModel>)Application.Current.Properties["RouterMap"];
                        FunctionKeyBarItemDataModel ActionItem = RouterDictionary["1"].functionKeyBarItems[5];
                        ActionItem.Header = Resources.Action;
                        ActionItem.Icon = GetIconBrush(Icon.Play, imageDecoration: ImageDecoration.Box);
                    }
                };
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_UI.Error(ex.Message);
            }
        }

        /// <summary>
        /// 状态和数据切换
        /// </summary>
        public void HandleChangeCurrentBatches()
        {
            try
            {
                Dictionary<string, RouterItemDataModel> RouterDictionary = (Dictionary<string, RouterItemDataModel>)Application.Current.Properties["RouterMap"];
                RouterDictionary["1"].functionKeyBarItems[5].IsEnabled = true;
                CurrentBatches = CurrentBatchesModel.BatchId;
                BoardsAmount = CurrentBatchesModel.BoardsAmount;
                MprGroupBatchs = Handle_Search.GetBorderListByBatch(CurrentBatches);
                TotalCompletionRate = Handle_Search.GetTotalCompletionRate(CurrentBatches);
                RemberBatchId = CurrentBatchesModel.BatchId;
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_UI.Error(ex.Message);
            }
        }

        /// <summary>
        /// 开始
        /// </summary>

        public void Action()
        {
            try
            {
                Dictionary<string, RouterItemDataModel> RouterDictionary = (Dictionary<string, RouterItemDataModel>)Application.Current.Properties["RouterMap"];
                FunctionKeyBarItemDataModel ActionItem = RouterDictionary["1"].functionKeyBarItems[2];
                List<T_Nesting_LabelTask> TasksList = Handle_Search.GetPrintTasksList().ToList();

                //点击开始按钮
                if (ActionItem.Header == Resources.Action || ActionItem.Header == "开始")
                {
                    SerilogHandle.Logger_System.Information("用户点击了开始按钮");
                    if (TotalCompletionRate != 100)
                    {
                        if (TasksList.Count != 0 && HomagGroup.Base.UI.Windows.MessageBox.Show(localText.There_are_currently_interrupted_or_unfinished_tasks__please_select_whether_to_resume_, localText.Prompt_message, MessageBoxButton.OKCancel, MessageBoxImage.Question) == MessageBoxResult.Cancel)
                        {
                            SerilogHandle.Logger_System.Information("用户选择了继续任务");
                            CurrentBatchesModel = List_BatchesModel.FirstOrDefault(s => s.BatchId == RemberBatchId);
                            Handle_Insert.InsertLabelTask(CurrentBatches);
                        }
                        else
                        {
                            SerilogHandle.Logger_System.Information("用户选择了重新生成任务");
                            string Id = TasksList.Count() == 0 ? RemberBatchId : TasksList[0].BatchId;
                            CurrentBatchesModel = List_BatchesModel.FirstOrDefault(s => s.BatchId == Id);
                            if (TasksList.Count == 0)
                                Handle_Insert.InsertLabelTask(Id);
                        }
                    }
                    else
                    {
                        CurrentBatchesModel = List_BatchesModel.FirstOrDefault(s => s.BatchId == RemberBatchId);
                        Handle_Insert.InsertLabelTask(CurrentBatches);
                    }

                    TableBack = GetHexadecimalColor("#f2f2f2");
                    MprSelectedState = false;
                    MprGroupBatchs = Handle_Search.GetBorderDetailsListByBatch(MprGroupBatchs);
                    TotalCompletionRate = Handle_Search.GetTotalCompletionRate();

                    ActionItem.Header = Resources.Pause;
                    ActionItem.Icon = GetIconBrush(Icon.PlayPause, imageDecoration: ImageDecoration.Box);
                }
                else
                {
                    SerilogHandle.Logger_System.Information("用户点击了暂停按钮");
                    BatchsSelectState = true;
                    MprSelectedState = true;
                    TableBack = null;
                    TotalCompletionRate = 0;
                    ActionItem.Header = Resources.Action;
                    ActionItem.Icon = GetIconBrush(Icon.Play, imageDecoration: ImageDecoration.Box);
                }
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_UI.Error(ex.Message);
            }
        }

        public void HandleOpenMprFile()
        {
            try
            {
                var data = new FileDialogData()
                {
                    InitialDirectory = Directory.GetCurrentDirectory(),
                    Features = FileDialogData.FeaturesModes.CanCreateFolders
                };
                if (UIAdjustments.CurrentThreadDialogManager.FileDialog.SelectDirectory(Application.Current.MainWindow, data) == true)
                {
                    new DealWithBatchFile().DealWithBatchFiles(data.FileName);
                    ViewloadedCommand();
                }

            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_UI.Error(ex.Message);
            }
        }

        public void PrintState()
        {
            try
            {
                printHistoryDialogViewModel = new PrintHistoryDialogViewModel();
                UIAdjustments.CurrentThreadDialogManager.ShowDialog<PrintHistoryDialog>(printHistoryDialogViewModel, null);
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_UI.Error(ex.Message);
            }
        }

        /// <summary>
        /// 板件详情
        /// </summary>
        /// <param name="obj"></param>
        public void HandleClickMprItem(int BoardInfpId)
        {
            try
            {
                partDetailsDialogViewModel = new PartDetailsDialogViewModel(BoardInfpId);
                UIAdjustments.CurrentThreadDialogManager.ShowDialog<PartDetailsDialog>(partDetailsDialogViewModel, null);
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_UI.Error(ex.Message);
            }
        }

        public void HandleReset(object sender = null, System.EventArgs e = null)
        {
            try
            {
                BatchsSelectState = true;
                CurrentBatchesModel = null;
                TableBack = null;
                MprSelectedState = true;
                CurrentBatches = null;
                BoardsAmount = null;
                if (MprGroupBatchs != null)
                {
                    MprGroupBatchs.Clear();
                }
                Dictionary<string, RouterItemDataModel> RouterDictionary = (Dictionary<string, RouterItemDataModel>)Application.Current.Properties["RouterMap"];
                FunctionKeyBarItemDataModel ActionItem = RouterDictionary["1"].functionKeyBarItems[5];
                ActionItem.IsEnabled = false;
                ActionItem.Header = Resources.Action;
                ActionItem.Icon = GetIconBrush(Icon.Play, imageDecoration: ImageDecoration.Box);
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_UI.Error(ex.Message);
            }
        }

        public void HandleCancelAllTasks()
        {
            try
            {
                string message = "";
                var state = HomagGroup.Base.UI.Windows.MessageBox.Show(Application.Current.MainWindow, localText.Remove_Current_Batch, localText.Prompt_message, localText.False, localText.True, MessageBoxImage.Asterisk, MessageBoxResult.Yes);
                if (state == MessageBoxResult.No)
                {
                    if (CurrentBatches != null)
                    {
                        message = Handle_Delete.DeleteBatchById(CurrentBatches);
                        HandleReset();
                    }
                    else
                    {
                        message = "请选择一个批次号！";
                    }
                    HomagGroup.Base.UI.Windows.MessageBox.Show(LocalizedText.CreateFromResourceManager(Resources.ResourceManager, message).ToString());
                }
                ViewloadedCommand();
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_UI.Error(ex.Message);
            }
        }

        public void RemoveMprCommand()
        {
            try
            {
                string message = "";
                foreach (var item in RemoveMprList)
                {
                    MprListModel mprListModel = item as MprListModel;
                    message = Handle_Delete.DeleteMprById(mprListModel.BoardInfoId);
                }
                ViewloadedCommand();

                HomagGroup.Base.UI.Windows.MessageBox.Show(LocalizedText.CreateFromResourceManager(Resources.ResourceManager, message).ToString());
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_UI.Error(ex.Message);
            }
        }

        #region Canvas

        /// <summary>
        ///
        /// </summary>
        public void CreateCanvas()
        {
            try
            {
                CreateImageCanvasView("s1", AppDomain.CurrentDomain.BaseDirectory + "CanvasImage/OrdinaryRoller.png", 0, 150, 650, 250, 80);
                CreateImageCanvasView("s2", AppDomain.CurrentDomain.BaseDirectory + "CanvasImage/BeltpulleySmall.png", 0, 158, 460, 250, 210);
                CreateImageCanvasView("s3", AppDomain.CurrentDomain.BaseDirectory + "CanvasImage/OrdinaryRoller.png", 0, 145, 310, 250, 170);
                CreateImageCanvasView("s4", AppDomain.CurrentDomain.BaseDirectory + "CanvasImage/BeltpulleyBig.png", 0, 150, 130, 250, 200);
                CreateImageCanvasView("H330", AppDomain.CurrentDomain.BaseDirectory + "CanvasImage/H330.png", 0, 370, 65, 650, 330);
                CreateImageCanvasView("s5", AppDomain.CurrentDomain.BaseDirectory + "CanvasImage/H330-后加长.png", 0, 980, 130, 330, 200);
                CreateImageCanvasView("s6", AppDomain.CurrentDomain.BaseDirectory + "CanvasImage/OrdinaryRoller.png", 0, 1050, 310, 250, 170);
                CreateImageCanvasView("s7", AppDomain.CurrentDomain.BaseDirectory + "CanvasImage/BeltpulleySmall.png", 0, 1065, 460, 250, 210);
                CreateImageCanvasView("s100", AppDomain.CurrentDomain.BaseDirectory + "CanvasImage/OrdinaryRoller.png", 0, 1055, 650, 250, 80);
                CreateImageCanvasView("H230", AppDomain.CurrentDomain.BaseDirectory + "CanvasImage/H230-L.png", 0, 370, 380, 750, 360);
                CreateSectionCanvasView();
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_UI.Error(ex.Message);
            }
        }

        /// <summary>
        /// 创建图片画布
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="imagePath"></param>
        /// <param name="strokeThickness"></param>
        /// <param name="left"></param>
        /// <param name="Top"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        public void CreateImageCanvasView(string Id, string imagePath, int strokeThickness, int left, int Top, int width, int height)
        {
            try
            {
                Rectangle ImageRectangle = new Rectangle
                {
                    Uid = Id,
                    Width = width,
                    Height = height,
                    Fill = CraeteImageBrushFill(imagePath),
                    Stroke = Brushes.Black,
                    StrokeThickness = strokeThickness,
                };

                StorageDataModels.Add(ImageRectangle.Uid, new StorageDataModel
                {
                    Uid = ImageRectangle.Uid,
                    Rectangle = ImageRectangle,
                    Width = ImageRectangle.Width,
                    Height = ImageRectangle.Height,
                    Left = left,
                    Top = Top,
                });
                Canvas.SetLeft(ImageRectangle, left);
                Canvas.SetTop(ImageRectangle, Top);
                Warehouse.Children.Add(ImageRectangle);
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_UI.Error(ex.Message);
            }
        }

        /// <summary>
        /// 创建点位画布
        /// </summary>
        public void CreateSectionCanvasView()
        {
            try
            {
                Canvas SectionCanvasView = new Canvas();
                var LocationDetailInfo = Handle_Search.GetLocationDetailInfo(true);

                DropDownList ModeDropList = new DropDownList
                {
                    Width = 250,
                    IsImageVisible = false,
                    Label = "Operating_mode",
                    ItemsSource = dropDownList.ItemsSource,
                    SelectedIndex = 0
                };

                foreach (var item in LocationDetailInfo)
                {
                    var grid = new Grid();
                    Ellipse container = new Ellipse
                    {
                        Width = 45,
                        Height = 45,
                        Fill = Brushes.White,
                        Stroke = Brushes.Green,
                        StrokeThickness = 3,
                    };

                    TextBlock textBlock = new TextBlock
                    {
                        Text = item.Position,
                        Foreground = Brushes.Green,
                        Background = Brushes.White,
                        FontSize = 17,
                        FontWeight = FontWeights.Bold,
                        HorizontalAlignment = HorizontalAlignment.Center,
                        VerticalAlignment = VerticalAlignment.Center
                    };
                    grid.Children.Add(container);
                    grid.Children.Add(textBlock);
                    Canvas.SetLeft(grid, (float)item.ComponentsCoor_Left);
                    Canvas.SetTop(grid, (float)item.ComponentsCoor_Top);
                    Canvas.SetZIndex(grid, 100000);
                    SectionCanvasView.Children.Add(grid);
                }
                Warehouse.Children.Add(SectionCanvasView);
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_UI.Error(ex.Message);
            }
        }

        private void ActionButtoClickCommand()
        {
            try
            {
                Handle_Delete.DeleteOnLineRecords();
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_UI.Error(ex.Message);
            }
        }

        #endregion Canvas

        #region DropDownList

        /// <summary>
        /// 加载DropDownList内容
        /// Load the DropDownList
        /// </summary>
        public void LoadDropDownList()
        {
            try
            {
                dropDownList = new DropDownList();
                var Modes = new List<string>() { { "Auto" } };//, { "Manual" } 
                dropDownList.ItemsSource = (Modes);
                dropDownList.SelectedIndex = 0;
                dropDownList.SelectionChanged += DropDownList_SelectionChanged;
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_UI.Error(ex.Message);
            }
        }

        /// <summary>
        /// DropDownList 选择变化事件
        /// SelectionChanged of DropDownList
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DropDownList_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            try
            {
                SelectedValue = ((DropDownList)sender).SelectedItem.ToString();
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_UI.Error(ex.Message);
            }
        }

        #endregion DropDownList

        /// <summary>
        ///自动运行板件
        /// </summary>
        /// <param name="boardInfoModel"></param>
        public void AutomaticRunningBoards(float Length, float Width)
        {
            try
            {
                Rectangle rectangle = new Rectangle
                {
                    Width = (double)Width / 10,
                    Height = (double)Length / 10,
                    Fill = GetHexadecimalColor("#d5771e"),
                };

                Canvas.SetLeft(rectangle, StorageDataModels[CurrentAdress].Left + StorageDataModels[CurrentAdress].Width - 50);
                Canvas.SetTop(rectangle, StorageDataModels[CurrentAdress].Top);
                Canvas.SetZIndex(rectangle, 10000);
                Warehouse.Children.Add(rectangle);
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_UI.Error(ex.Message);
            }
        }

        #region Infeed
        /// <summary>
        /// 入库功能开启
        /// Open the infeed function
        /// </summary>
        public void ClickInFeedCommand()
        {
            try
            {
                if (this.InFeedCheck)
                {
                    ActivatedInfeed();
                }
                else
                {
                    UnactivatedInfeed();
                }
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_UI.Error(ex.Message);
            }
        }

        public void ActivatedInfeed()
        {
            try
            {
                SerilogHandle.Logger_System.Information("用户开启了进料功能");
                this.InFeedCheck = true;
                this.InFeedState = DeviceState.Ok;
                this.InFeedEnable = !RunEmptyCheck;
                Utility.Globle.isInfeedAreaActive = true;
                UpdateSessionTimer.Start();
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_UI.Error(ex.Message);
            }
        }

        public void UnactivatedInfeed()
        {
            try
            {
                SerilogHandle.Logger_System.Information("用户关闭了进料功能");
                this.InFeedCheck = false;
                this.InFeedState = DeviceState.Off;
                this.InFeedEnable = !RunEmptyCheck;
                Utility.Globle.isInfeedAreaActive = false;
                UpdateSessionTimer.Stop();
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_UI.Error(ex.Message);
            }
        }
        #endregion Infeed

        #region Printer

        /// <summary>
        /// 出库功能开启
        /// Open the outfeed function
        /// </summary>
        public void ClickPrinterCommand()
        {
            try
            {
                if (this.PrinterCheck)
                {
                    ActivatedPrinter();
                    PrinterHandle outfeedHandle = new PrinterHandle();
                }
                else
                {
                    UnactivatedOutfeed();
                }
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_UI.Error(ex.Message);
            }
        }

        public void ActivatedPrinter()
        {
            try
            {
                this.PrinterCheck = true;
                this.OutFeedState = DeviceState.Ok;
                this.PrinterEnable = !RunEmptyCheck;
                Utility.Globle.isOutfeedAreaActive = true;
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_UI.Error(ex.Message);
            }
        }

        public void UnactivatedOutfeed()
        {
            try
            {
                this.PrinterCheck = false;
                this.OutFeedState = DeviceState.Off;
                this.PrinterEnable = !RunEmptyCheck;
                Utility.Globle.isOutfeedAreaActive = false;
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_UI.Error(ex.Message);
            }
        }

        #endregion Printer

        #region Cancel All

        /// <summary>
        /// 取消所有功能点击事件
        /// Cancel all function
        /// </summary>
        public void ClickCancelAllCommand()
        {
            try
            {
                CancelAll();
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_UI.Error(ex.Message);
            }
        }

        /// <summary>
        /// 取消所有功能
        /// </summary>
        public void CancelAll()
        {
            try
            {
                UnactivatedRunEmpty();
                UnactivatedInfeed();
                UnactivatedOutfeed();
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_UI.Error(ex.Message);
            }
        }

        #endregion Cancel All

        #region Run Empty

        /// <summary>
        /// 清空线体所有板件
        /// Empty all the parts of the line
        /// </summary>
        public void ClickRunEmptyCommand()
        {
            try
            {
                ActivatedInfeed();
                ActivatedPrinter();

                if (RunEmptyCheck)
                {
                    Utility.Globle.isRunEmptyActive = true;
                    Task.Factory.StartNew(async () =>
                    {
                        string callBackMsg = await Handle_RunEmpty.RunEmpty();
                        CancelAll();
                        HomagGroup.Base.UI.Windows.MessageBox.Show(LocalizedText.CreateFromResourceManager(PropertiesLibarary.Properties.Resources.ResourceManager, callBackMsg).ToString());
                    });
                }
                else
                {
                    Utility.Globle.isRunEmptyActive = false;
                }
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_UI.Error(ex.Message);
            }
        }

        /// <summary>
        ///
        /// </summary>
        public void UnactivatedRunEmpty()
        {
            try
            {
                RunEmptyCheck = false;
                Utility.Globle.isRunEmptyActive = false;
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_UI.Error(ex.Message);
            }
        }

        #endregion Run Empty
    }
}